package com.example.myapplication;

import java.util.ArrayList;
import java.util.List;
import android.app.Activity;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.*;
import android.view.GestureDetector;
import android.view.GestureDetector.OnGestureListener;
import android.view.Gravity;
import android.view.MotionEvent;
import android.view.TextureView;
import android.view.View;
import android.view.View.OnTouchListener;
import android.view.WindowManager;
import android.widget.LinearLayout;
import android.widget.LinearLayout.LayoutParams;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;


public class MainActivity extends Activity {
    private static Thread thread=null;
    final int RIGHT = 0;
    final int LEFT = 1;
    final int UP=2;
    final int DOWN=3;
    Boolean isPut_left=false;
    Boolean isPut_right=false;
    Boolean isPut_up=false;
    Boolean isPut_down=false;
    TextView[][] textGroup;
    GestureDetector gestureDetector=null;
    RelativeLayout layout=null;
    TextView textView=null;
    private int score=0;
    private Handler handler=new Handler(){

        @Override
        public void handleMessage(Message msg) {
            // TODO Auto-generated method stub
            switch (msg.what) {
                case 1:textView.setText("分数："+Integer.toString(score));

                    break;

                default:
                    break;
            }
        }

    };
    /**
     * 接收滑动事件
     */
    private GestureDetector.OnGestureListener onGestureListener =
            new GestureDetector.SimpleOnGestureListener() {
                @Override
                public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX,
                                       float velocityY) {
                    float x = e2.getX() - e1.getX();
                    float y = e2.getY() - e1.getY();

                    float d_x;
                    float d_y;

                    if(x>=0){
                        d_x=x;
                    }else{
                        d_x=-x;
                    }

                    if(y>=0){
                        d_y=y;
                    }else{
                        d_y=-y;
                    }

                    if (x > 0&&x > d_y) {
                        doResult(RIGHT);
                    }
                    if (x < 0&&-x>d_y) {
                        doResult(LEFT);
                    }
                    if (y > 0&&y>d_x){
                        doResult(DOWN);
                    }
                    if (y < 0&&(-y)>d_x){
                        doResult(UP);
                    }
                    return true;
                }
            };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        layout=new RelativeLayout(this);
        layout=(RelativeLayout)findViewById(R.id.layout);

        textView=new TextView(this);
        textView=(TextView) findViewById(R.id.score);


        DisplayMetrics dm = new DisplayMetrics();
        getWindowManager().getDefaultDisplay().getMetrics(dm);
        int width = dm.widthPixels;    //得到宽度

        textGroup=init(width);
        putItem(textGroup);
        drawColor(textGroup);

        gestureDetector = new GestureDetector(MainActivity.this,onGestureListener);


    }

    public boolean onTouchEvent(MotionEvent event) {
        return gestureDetector.onTouchEvent(event);
    }

    public void doResult(int action) {

        switch (action) {
            case RIGHT:
                rightRemove(textGroup);
                mergeRight(textGroup);



                if(isPut_right){
                    rightRemove(textGroup);
                    isPut_right=false;
                    putItem(textGroup);
                }

                break;

            case LEFT:
                leftRemove(textGroup);
                mergeLeft(textGroup);

                if(isPut_left){
                    leftRemove(textGroup);

                    isPut_left=false;
                    putItem(textGroup);
                }

                break;

            case UP:
                upRemove(textGroup);
                mergeUp(textGroup);
                if(isPut_up){
                    upRemove(textGroup);
                    isPut_up=false;

                    putItem(textGroup);
                }

                break;
            case DOWN:
                downRemove(textGroup);

                mergeDown(textGroup);
                if(isPut_down){
                    downRemove(textGroup);
                    isPut_down=false;
                    putItem(textGroup);
                }

                break;
        }
    }

    /**
     * 初始化界面
     * @param width
     * @return
     */

    public TextView[][] init(int width){
        TextView[][] textGroup=new TextView[5][5];
        for (int i = 1; i <=4; i++) {
            for (int j = 1; j <= 4; j++) {
                RelativeLayout.LayoutParams lp=new RelativeLayout.LayoutParams((width-5*10)/4, (width-5*10)/4);
                lp.leftMargin=10;
                lp.bottomMargin=10;

                textGroup[i][j]=new TextView(this);
                textGroup[i][j].setId(i*4+j);

                if(j==1){
                    if(i==1){
                        lp.addRule(RelativeLayout.ALIGN_PARENT_TOP,RelativeLayout.TRUE);
                    }else{
                        lp.addRule(RelativeLayout.BELOW,(i-1)*4+j);
                    }
                }
                else{
                    lp.addRule(RelativeLayout.RIGHT_OF,i*4+j-1);
                    lp.addRule(RelativeLayout.ALIGN_TOP,i*4+j-1);
                    Log.d("id", Integer.toString(i*4+j));
                }
                textGroup[i][j].setBackgroundColor(Color.YELLOW);
                textGroup[i][j].setText("0");
                textGroup[i][j].setTextSize(25);
                textGroup[i][j].setGravity(Gravity.CENTER);
                textGroup[i][j].setLayoutParams(lp);
                layout.addView(textGroup[i][j]);

            }
        }
        return textGroup;
    }

    public void putItem(TextView[][] group){
        List<TextView> list=new ArrayList<TextView>();
        for (int i = 1; i <=4; i++) {
            for (int j = 1; j <=4; j++) {
                if(group[i][j].getText().equals("0")){
                    list.add(group[i][j]);
                }
            }
        }
        int n=(int) ((Math.random()*list.size()));
        if(Math.random()>=0.25){
            list.get(n).setText("2");
        }
        else{
            list.get(n).setText("4");
        }
        drawColor(textGroup);
    }

    public void drawColor(TextView[][] group){
        for (int i = 1; i <= 4; i++) {
            for (int j = 1; j <= 4; j++) {
                int n=Integer.parseInt((String) group[i][j].getText());
                switch (n) {
                    case 0:group[i][j].setTextSize(0);
                        group[i][j].setBackgroundColor(Color.parseColor("#CCC0B3"));
                        break;
                    case 2:group[i][j].setTextSize(25);
                        group[i][j].setBackgroundColor(Color.parseColor("#EEE4DA"));
                        break;
                    case 4:group[i][j].setTextSize(25);
                        group[i][j].setBackgroundColor(Color.parseColor("#EDE0C8"));
                        break;
                    case 8:group[i][j].setTextSize(25);
                        group[i][j].setBackgroundColor(Color.parseColor("#F2B179"));
                        break;
                    case 16:group[i][j].setTextSize(25);
                        group[i][j].setBackgroundColor(Color.parseColor("#F49563"));
                        break;
                    case 32:group[i][j].setTextSize(25);
                        group[i][j].setBackgroundColor(Color.parseColor("#F5794D"));
                        break;
                    case 64:group[i][j].setTextSize(25);
                        group[i][j].setBackgroundColor(Color.parseColor("#F55D37"));
                        break;
                    case 128:group[i][j].setTextSize(25);
                        group[i][j].setBackgroundColor(Color.parseColor("#EEE863"));
                        break;
                    case 256:group[i][j].setTextSize(25);
                        group[i][j].setBackgroundColor(Color.parseColor("#EDB04D"));
                        break;
                    case 512:group[i][j].setTextSize(25);
                        group[i][j].setBackgroundColor(Color.parseColor("#ECB04D"));
                        break;
                    case 1024:group[i][j].setTextSize(25);
                        group[i][j].setBackgroundColor(Color.parseColor("#EB9437"));
                        break;
                    case 2048:group[i][j].setTextSize(25);
                        group[i][j].setBackgroundColor(Color.parseColor("#EA7821"));
                        break;
                    default:
                        break;
                }
            }
        }
    }

    /**
     * 合并
     * @param group
     */
    public void mergeLeft(TextView[][] group){
        for (int i = 1; i <= 4; i++) {
            for (int j = 1; j <= 3; j++) {
                int a=Integer.parseInt((String) group[i][j].getText());
                int b=Integer.parseInt((String) group[i][j+1].getText());

                if(a==b&&a!=0){
                    group[i][j].setText(Integer.toString(a+b));
                    group[i][j+1].setText("0");
                    isPut_left=true;
                    score+=a*2;
                    System.out.println(score);
                    updateScore();
                }

            }
        }
        drawColor(textGroup);
    }

    public void mergeRight(TextView[][] group){
        for (int i = 1; i <=4; i++) {
            for (int j = 4; j >=2; j--) {
                int a=Integer.parseInt((String) group[i][j].getText());
                int b=Integer.parseInt((String) group[i][j-1].getText());


                if(a==b&&a!=0){
                    group[i][j].setText(Integer.toString(a+b));
                    group[i][j-1].setText("0");
                    isPut_right=true;
                    score+=a*2;
                    System.out.println(score);
                    updateScore();

                }
            }
        }
        drawColor(textGroup);
    }

    public void mergeUp(TextView[][] group){
        for (int i = 1; i <=3; i++) {
            for (int j = 1; j <=4; j++) {
                int a=Integer.parseInt((String) group[i][j].getText());
                int b=Integer.parseInt((String) group[i+1][j].getText());

                if(a==b&&a!=0){
                    group[i][j].setText(Integer.toString(a+b));
                    group[i+1][j].setText("0");
                    isPut_up=true;
                    score+=a*2;
                    System.out.println(score);
                    updateScore();

                }
            }
        }
        drawColor(textGroup);
    }

    public void mergeDown(TextView[][] group){
        for (int i = 4; i >=2; i--) {
            for (int j = 1; j <=4; j++) {
                int a=Integer.parseInt((String) group[i][j].getText());
                int b=Integer.parseInt((String) group[i-1][j].getText());

                if(a==b&&a!=0){
                    group[i][j].setText(Integer.toString(a+b));
                    group[i-1][j].setText("0");
                    isPut_down=true;
                    score+=a*2;
                    System.out.println(score);
                    updateScore();

                }
            }
        }
        drawColor(textGroup);
    }

    /**
     * 移除空格
     * @param group
     */
    public void leftRemove(TextView[][] group){

        for (int i = 1; i <= 4; i++) {
            for (int k = 1; k <= 3; k++) {
                for (int j = 1; j <= 3; j++) {
                    int a=Integer.parseInt((String) group[i][j].getText());
                    int b=Integer.parseInt((String) group[i][j+1].getText());

                    if(a==0&&b!=0){
                        group[i][j].setText(group[i][j+1].getText());
                        group[i][j+1].setText("0");
                        isPut_left=true;
                        Log.d("yyyyyc", (String) group[i][j].getText());
                    }
                }

            }

        }

        drawColor(textGroup);
    }

    public void rightRemove(TextView[][] group){
        for (int i = 1; i <= 4; i++) {
            for (int k = 1; k <= 3; k++) {
                for (int j = 4; j >=2; j--) {
                    int a=Integer.parseInt((String) group[i][j].getText());
                    int b=Integer.parseInt((String) group[i][j-1].getText());

                    if(a==0&&b!=0){
                        group[i][j].setText(group[i][j-1].getText());
                        group[i][j-1].setText("0");
                        isPut_right=true;
                    }
                }

            }
        }
        drawColor(textGroup);
    }

    public void upRemove(TextView[][] group){
        for (int j = 1; j <= 4; j++) {
            for (int k = 1; k <= 3; k++){
                for (int i = 1; i <=3; i++)  {
                    int a=Integer.parseInt((String) group[i][j].getText());
                    int b=Integer.parseInt((String) group[i+1][j].getText());


                    if(a==0&&b!=0){
                        group[i][j].setText(group[i+1][j].getText());
                        group[i+1][j].setText("0");
                        isPut_up=true;
                    }
                }

            }
        }
        drawColor(textGroup);
    }

    public void downRemove(TextView[][] group){
        for (int j = 1; j <=4; j++) {
            for (int k = 1; k <= 3; k++) {
                for (int i = 4; i >= 2; i--) {
                    int a=Integer.parseInt((String) group[i][j].getText());
                    int b=Integer.parseInt((String) group[i-1][j].getText());


                    if(a==0&&b!=0){
                        group[i][j].setText(group[i-1][j].getText());
                        group[i-1][j].setText("0");
                        isPut_down=true;
                    }
                }

            }
        }
        drawColor(textGroup);
    }

    public void updateScore() {
        thread =new Thread(new Runnable() {

            @Override
            public void run() {
                // TODO Auto-generated method stub
                Message msg=new Message();
                msg.what=1;
                handler.sendMessage(msg);
            }
        });
        thread.run();
    }

}
